#target illustrator

(function () {
    if (app.documents.length === 0) {
        alert("Open a document before running this script.");
        return;
    }

    var presetName = "Redraw_1";
    var doc = app.activeDocument;
    var selection = doc.selection;

    if (!selection || selection.length === 0) {
        alert("Select one or more raster items before running the script.");
        return;
    }

    var presets = app.tracingPresetsList || [];
    var hasPreset = false;
    for (var p = 0; p < presets.length; p++) {
        if (presets[p] === presetName) {
            hasPreset = true;
            break;
        }
    }

    if (!hasPreset) {
        alert('Tracing preset "' + presetName + '" was not found.');
        return;
    }

    var targets = [];
    collectRasterItems(selection, targets);

    if (targets.length === 0) {
        alert("No raster items were found in the selection.");
        return;
    }

    var traced = 0;
    var skipped = 0;

    for (var i = 0; i < targets.length; i++) {
        var raster = targets[i];

        if (!raster || raster.typename !== "RasterItem" || raster.locked || raster.hidden) {
            skipped++;
            continue;
        }

        try {
            var tracing = raster.trace();
            if (!tracing) {
                skipped++;
                continue;
            }

            tracing.tracingOptions.loadFromPreset(presetName);

            if (typeof tracing.applyTracing === "function") {
                tracing.applyTracing();
            } else if (tracing.tracingOptions) {
                if (typeof tracing.tracingOptions.applyTracing === "function") {
                    tracing.tracingOptions.applyTracing();
                } else if (typeof tracing.tracingOptions.apply === "function") {
                    tracing.tracingOptions.apply();
                }
            }

            traced++;
        } catch (err) {
            skipped++;
        }
    }

    var report = "Tracing preset applied to " + traced + " item(s).";
    if (skipped > 0) {
        report += "\nSkipped: " + skipped;
    }
    alert(report);
})();

function collectRasterItems(items, bucket) {
    if (!items || !bucket) {
        return;
    }

    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (!item) {
            continue;
        }

        var typeName = item.typename;
        if (typeName === "RasterItem") {
            bucket.push(item);
        } else if (item.pageItems && item.pageItems.length) {
            collectRasterItems(item.pageItems, bucket);
        }
    }
}
